package com.itheima.reggie.aspect;


import com.itheima.reggie.common.R;
import com.itheima.reggie.log.MyLog;
import com.itheima.reggie.log.SysLog;
import com.itheima.reggie.service.SysLogService;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

@Aspect
@Component
public class SysLogAspect {



        @Autowired
        private SysLogService sysLogService;

        //定义切点 @Pointcut
        //在注解的位置切入代码
        @Pointcut("@annotation( com.itheima.reggie.log.MyLog)")
        public void logPoinCut() {
        }

        //切面 配置通知
        @AfterReturning(value = "logPoinCut()",returning = "res")
        public void saveSysLog(JoinPoint joinPoint, R res) {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            Method method = signature.getMethod();
            MyLog myLog = method.getAnnotation(MyLog.class);
            //保存日志的实体类
            SysLog sysLog = new SysLog();
            if (myLog != null) {
                String value = myLog.value();//获取自定义注解的value
                //保存获取的操作
                sysLog.setOperation(value);
            }

            //获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            //获取请求的方法名
            String methodName = method.getName();
            sysLog.setMethod(className + "." + methodName);
           //获取请求
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            HttpServletRequest request = attributes.getRequest();
            String requestURL = request.getRequestURL().toString();
            //设置请求路径
            sysLog.setUrl(requestURL);
            //设置本次操作是否成功
            Integer code = res.getCode();
            int c1=code;
            if (code!=null){
                if (c1==1){
                    sysLog.setTorf("操作成功");
                }
                else if (code==0){
                    sysLog.setTorf("操作失败");
                }
           }
            //设置员工id
            String employeeid = String.valueOf(request.getSession().getAttribute("employee"));
            sysLog.setEmployeeId(employeeid);

           //调用service保存SysLog实体类到数据库
            sysLogService.save(sysLog);

        }

    }

